<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="10">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsersLiset">
            <el-button slot="append" icon="el-icon-search" @click="getUsersLiset"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加学生</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="todo" style="width: 100%" border stripe resizable>
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scoped">
            <el-switch v-model="scoped.row.mg_state" @change="change(scoped.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-tooltip class="item" effect="dark" content="修改角色" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip class="item" effect="dark" content="删除角色" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUsers(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 分配角色按钮 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showUser(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页栏 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 6, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="todol"> </el-pagination>
    </el-card>
    <!-- 对话框主体 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
      <!-- 对话框头部 -->
      <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addValidate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对象对话框主体 -->
    <el-dialog title="修改用户" :visible.sync="dialogVisibleto" width="50%" @close="addDialogClosed">
      <!-- 修改对象对话框头部 -->
      <el-form :model="ruleFormto" :rules="rules" ref="ruleFormRef" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="ruleFormto.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleFormto.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="ruleFormto.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 修改对象对话框底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleto = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="提示" :visible.sync="setVisible" width="30%">
      <div>
        <p>当前用户:{{show.username}}</p>
        <p>当前角色:{{show.role_name}}</p>
        <p>
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option v-for="item in userInfo" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setVisible = false">取 消</el-button>
        <el-button type="primary" @click="setVisibles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    var checkEmail = (rule, value, cb) => {
      const regEali =
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
      if (regEali.test(value)) {
        return cb()
      }
      cb(new Error('请输入正确的邮箱'))
    }
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入正确的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      todo: [],
      on: 0,
      value: true,
      todol: 0,
      mg_state: false,
      dialogVisible: false,
      setVisible: false,
      // 添加的数据对象
      ruleForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      ruleFormto: {
        username: '',
        email: '',
        mobile: ''
      },
      dialogVisibleto: false,
      show: '',
      userInfo: '',
      selectRoleId: '',
      // 分页里面的小bug解决方案
      a: ''
    }
  },
  methods: {
    // 获取api数据
    async getUsersLiset () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message('用户获取失败')
      this.todo = res.data.users
      this.todol = res.data.total
      this.mg_state = res.mg_state
      console.log(this.todo)
      console.log(res)
    },
    // 分页选择区域
    handleSizeChange (newPage) {
      this.queryInfo.pagesize = newPage
      this.a = newPage
      this.getUsersLiset()
    },
    // 分页选择区域
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUsersLiset()
    },
    // 分页下一页或者上一页或者点击选择
    async change (scoped) {
      const { data: res } = await this.$http.put(
        `users/${scoped.id}/state/${scoped.mg_state}`
      )
      if (res.meta.status !== 200) {
        scoped.mg_state = !scoped.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 重置对话框
    addDialogClosed () {
      this.$refs.ruleFormRef.resetFields()
    },
    // 添加用户验证和添加用户
    addValidate () {
      this.$refs.ruleFormRef.validate(async (val) => {
        if (val) {
          this.dialogVisible = false
          const { data: res } = await this.$http.post('users', this.ruleForm)
          if (res.meta.status !== 201) {
            this.$message.error(res.meta.msg)
          } else {
            this.$message.success('添加用户成功')
            this.getUsersLiset()
          }
        } else {
          this.dialogVisible = true
          this.$message.error('请按照规定输入')
        }
      })
    },
    // 修改用户按钮的弹窗
    async showEditDialog (id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户数据失败')
      }
      this.ruleFormto = res.data
      this.dialogVisibleto = true
    },
    // 修改用户
    add () {
      this.$refs.ruleFormRef.validate(async (val) => {
        if (!val) return
        const { data: res } = await this.$http.put(
          'users/' + this.ruleFormto.id,
          {
            email: this.ruleFormto.email,
            mobile: this.ruleFormto.mobile
          }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        this.dialogVisibleto = false
        this.getUsersLiset()
        this.$message.success('修改成功')
      })
    },
    // 删除角色
    async delUsers (id) {
      // 删除用户的弹窗
      const a = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      // 删除成功
      if (a === 'confirm') {
        const { data: res } = await this.$http.delete('users/' + id)
        this.$message.success(res.meta.msg)
        this.queryInfo.pagenum = this.a
        this.getUsersLiset()
      }
    },
    // 分配角色
    async showUser (showInfo) {
      this.userInfo = ''
      this.selectRoleId = ''
      this.show = showInfo
      const { data: res } = await this.$http.get('roles')
      this.userInfo = res.data
      this.setVisible = true
    },
    // 点击按钮修改分配角色
    async setVisibles () {
      if (!this.selectRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.show.id}/role`, {
        rid: this.selectRoleId
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('更新成功')
      this.getUsersLiset()
      this.setVisible = false
    }
  },
  mounted () {
    this.getUsersLiset()
  }
}
</script>

<style scoped></style>
